Ext.Loader.setConfig( {
	enabled : true
});

Ext.require( [ '*' ]);

Ext.onReady(function() {
	// Define our data model
		Ext.define('amazonprice', {
			extend : 'Ext.data.Model',
			fields : [ {
				name : 'taskNo',
				type : 'float'
			}, 'amazonItemId', 'amazonItemPrice', 'amazonItemName', 'shopItemId', 'shopItemName', 'shopItemPrice',
			{
				name : 'startPrice',
				type : 'float'
			}, {
				name : 'minPrice',
				type : 'float'
			}, {
				name : 'startTime',
				type: 'date',
				dateFormat:'time'
			}, 'status', 'quantity','condition'],
			idProperty : 'taskNo'
		});

		// create the Data Store
		var store = Ext.create('Ext.data.Store', {
			autoLoad : true,
			pageSize : 20,
			model : 'amazonprice',
			remoteSort : false,
			proxy : {
				type : 'ajax',
				url : 'doGetAllTask/',
				reader : {
					root : 'results',
					totalProperty : 'totalCount'
				}
			}
		});

		function getStatusText(val){
			if(val == 0){
				return "×停止中";
			}else if (val == 1){
				return "○運行中";
			}else if (val == 3){
				return "×売り切れ";
			}

		}

		function getConditionText(val){
			if(val == 1){
				return "新品";
			}else if (val == 2){
				return "中古";
			}else if (val == 3){
				return "×売り切れ";
			}

		}

		// create the grid and specify what field you want
		// to use for the editor at each column.
		var sm = Ext.create('Ext.selection.CheckboxModel');
		var grid = Ext.create('Ext.grid.Panel', {
			store : store,
			columnLines : true,
			selModel: sm,
			height :510,
			columns : [ {
				header : 'Ｎｏ．',
				dataIndex : 'taskNo',
				sortable : true,
				width : 40
			}, {
				header : 'ASIN',
				dataIndex : 'amazonItemId',
				sortable : true,
				width : 100
			}, {
				header : '出品者SKU',
				dataIndex : 'shopItemId',
				width : 120
			}, {
				header : '商品名',
				dataIndex : 'amazonItemName',
				flex : 1
			}, {
				header : 'コンディション',
				dataIndex : 'condition',
				renderer:getConditionText,
				width : 80
			}, {
				header : '開始価格',
				renderer: Ext.util.Format.numberRenderer('0,000'),
				dataIndex : 'startPrice',
				width : 60
			}, {
				header : '最低価格',
				renderer: Ext.util.Format.numberRenderer('0,000'),
				dataIndex : 'minPrice',
				width : 60
//			} , {
//				header : '最安価格',
//				renderer: Ext.util.Format.numberRenderer('0,000'),
//				dataIndex : 'amazonItemPrice',
//				width : 60
			} , {
				header : '当店価格',
				renderer: Ext.util.Format.numberRenderer('0,000'),
				dataIndex : 'shopItemPrice',
				width : 60
			} , {
//				header : '在庫数',
//				dataIndex : 'quantity',
//				width : 60
//			}, {
				header : '開始日時',
				dataIndex : 'startTime',
				format: 'Y-m-d H:i',
				xtype: 'datecolumn',
				width : 120
			}, {
				header : '運行状況',
				dataIndex : 'status',
				renderer:getStatusText,
				width : 60
			} ],
			tbar : [ {
				text : '<div style="font-size:13px;">タスク追加</div>',
				iconCls : 'add',
				handler : addTask
			}, {
				itemId : 'taskPause',
				text : 'タスク一時停止',
				iconCls : 'remove',
				handler : pauseTask,
				disabled : true
			}, {
				itemId : 'taskRestart',
				text : 'タスク再開',
				iconCls : 'start',
				handler : restartTask,
				disabled : true
			}, {
				itemId : 'taskDelete',
				text : 'タスク削除',
				iconCls : 'delete',
				handler : deleteTask,
				disabled : true
			}, {
				itemId : 'taskEdit',
				text : 'タスク修正',
				iconCls : 'edit',
				handler : editTask,
				disabled : true
			} , {
				itemId : 'setKankaku',
				text : '間隔時間設定',
				iconCls : 'setting',
				handler : function() {
					Ext.Ajax.request({
					    url: 'doGetKankakuTime/',
					    success: function(response, opts) {
							if(response.responseText){
								settingPanel.down("#kankakuTime").setValue(response.responseText);
								settingWin.show();
							}
					    },
					    failure: function(response, opts) {
					        console.log('server-side failure with status code ' + response.status);
					    }
					});
				}
			} ],
			listeners : {
				'selectionchange' : function(view, records) {
					if(records.length>0){
						var status = records[0].get('status');
						if(status == 0||status == 3){
							grid.down('#taskRestart').setDisabled(false);
						}
						if(status==1){
							grid.down('#taskPause').setDisabled(false);
						}
						grid.down('#taskDelete').setDisabled(false);
						grid.down('#taskEdit').setDisabled(false);
					}else{
						grid.down('#taskRestart').setDisabled(true);
						grid.down('#taskPause').setDisabled(true);
						grid.down('#taskDelete').setDisabled(true);
						grid.down('#taskEdit').setDisabled(true);
					}
				},

				itemcontextmenu:rightClickFn
			},
//	        bbar: Ext.create('Ext.PagingToolbar', {
//	            store: store,
//	            displayInfo: true,
//	            displayMsg: 'Displaying topics {0} - {1} of {2}',
//	            emptyMsg: "No topics to display"
//	        }),
			viewConfig : {
				forceFit : true,
				getRowClass : function(record,rowIndex,rowParams,store){
					if(record.data.status==0){
						return 'x-grid-record-stop';
					}else if(record.data.status==1){
						return 'x-grid-record-running';
					}else if(record.data.status==3){
						return 'x-grid-record-soldout';
					}else{
						return '';
					}
				}
			}
		});

		function addTask() {
			newWin.setTitle('タスク追加');
			amazonPricePanel.down("#asin").setValue("");
			amazonPricePanel.down("#amazonItemName").setValue("");
			amazonPricePanel.down("#asin1").setValue("");
			amazonPricePanel.down("#amazonItemPrice").setValue("");
			amazonPricePanel.down("#amazonShop").setValue("");
			amazonPricePanel.down("#amazonItemShippingPrice").setValue("");
			amazonPricePanel.down("#minPrice").setValue("");
			amazonPricePanel.down("#sku").setValue("");
			amazonPricePanel.down("#shopItemName").setValue("");
			amazonPricePanel.down("#shopItemPrice").setValue("");
			amazonPricePanel.down("#shopItemCondition").setValue("");
			amazonPricePanel.down("#shopItemQuantity").setValue("");
			amazonPricePanel.down("#minPrice").setValue("");
			amazonPricePanel.down("#condition").setValue({"rb":"1"});
			amazonPricePanel.down("#taskNo").setValue("");
			amazonPricePanel.down("#status").setValue("");
			newWin.show();
		}

		function pauseTask() {
			var sm = grid.getSelectionModel();

		    Ext.MessageBox.show({
		           title:'タスク停止',
		           msg: sm.getSelection()[0].get("amazonItemName")+'<br/>を停止しでも宜しいでしょうか?',
		           buttons: Ext.MessageBox.YESNO,
		           fn: function(btn){
				    	if(btn=='yes'){
							Ext.Ajax.request({
							    url: 'updateTask/',
							    params:{
									taskNo:sm.getSelection()[0].get("taskNo"),
									status:0
								},
							    success: function(response, opts) {
									if(response.responseText=="success"){
										var selectNode =grid.getSelectionModel().getSelection();

								        Ext.MessageBox.show({
								            title: 'information',
								            msg: 'タスク停止成功',
								            buttons: Ext.MessageBox.OK,
								            icon: 'ext-mb-info'
								        });

										store.load({callback :function(){
											if(selectNode.length>0){
												grid.getSelectionModel().select(selectNode[0].index);
											}
										}
										});

									}
							    },
							    failure: function(response, opts) {
							        console.log('server-side failure with status code ' + response.status);
							    }
							});
				    	}
				   },
		           icon: 'ext-mb-question'
		    });
		}

		function deleteTask() {
			var sm = grid.getSelectionModel();
			var amazonItemName = sm.getSelection()[0].get("amazonItemName");
			var selectCount = sm.getSelection().length;
			var taskNos ="";
			for(var i=0;i<selectCount;i++){
				taskNos +=sm.getSelection()[i].get("taskNo")+",";
			}
			
		    Ext.MessageBox.show({
		           title:'タスク削除',
		           msg: '選択の <font color="red" size="+2">'+selectCount+'</font> 件を削除しでも宜しいでしょうか?',
		           buttons: Ext.MessageBox.YESNO,
		           fn: function(btn){
				    	if(btn=='yes'){
							Ext.Ajax.request({
							    url: 'doDeleteTask/',
							    params:{
									taskNo:taskNos
								},
							    success: function(response, opts) {
									var selectNode =grid.getSelectionModel().getSelection();

							        Ext.MessageBox.show({
							            title: 'information',
							            msg: 'タスク削除成功',
							            buttons: Ext.MessageBox.OK,
							            icon: 'ext-mb-info'
							        });

									store.load({callback :function(){
//										if(selectNode.length>0){
//											grid.getSelectionModel().select(selectNode[0].index);
//										}
										}
									});

							    },
							    failure: function(response, opts) {
							        console.log('server-side failure with status code ' + response.status);
							    }
							});
				    	}
				   },
		           icon: 'ext-mb-question'
		    });
		}

		function restartTask() {
			var sm = grid.getSelectionModel();

			Ext.Ajax.request({
			    url: 'updateTask/',
			    params:{
					taskNo:sm.getSelection()[0].get("taskNo"),
					status:1
				},
			    success: function(response, opts) {
					if(response.responseText=="success"){

				        Ext.MessageBox.show({
				            title: 'information',
				            msg: 'タスク再開成功',
				            buttons: Ext.MessageBox.OK,
				            icon: 'ext-mb-info'
				        });

						var selectNode =grid.getSelectionModel().getSelection();
						store.load({callback :function(){
								if(selectNode.length>0){
									grid.getSelectionModel().select(selectNode[0].index);
								}
							}
						});
					}
			    },
			    failure: function(response, opts) {
			        console.log('server-side failure with status code ' + response.status);
			    }
			});

		}

		function editTask() {
			newWin.setTitle('タスク修正');
			var sm = grid.getSelectionModel();

			amazonPricePanel.down("#asin").setValue(sm.getSelection()[0].get("amazonItemId"));
			amazonPricePanel.down("#asin1").setValue(sm.getSelection()[0].get("amazonItemId"));
			amazonPricePanel.down("#amazonItemName").setValue("");
			amazonPricePanel.down("#amazonItemPrice").setValue("");
			amazonPricePanel.down("#amazonShop").setValue("");
			amazonPricePanel.down("#amazonItemShippingPrice").setValue("");
			amazonPricePanel.down("#shopItemCondition").setValue("");
			amazonPricePanel.down("#minPrice").setValue("");
			amazonPricePanel.down("#sku").setValue(sm.getSelection()[0].get("shopItemId"));
			amazonPricePanel.down("#shopItemName").setValue("");
			amazonPricePanel.down("#shopItemPrice").setValue("");
			amazonPricePanel.down("#shopItemQuantity").setValue("");
			amazonPricePanel.down("#minPrice").setValue(sm.getSelection()[0].get("minPrice"));
			amazonPricePanel.down("#condition").setValue({"rb":sm.getSelection()[0].get("condition")});
			amazonPricePanel.down("#taskNo").setValue(sm.getSelection()[0].get("taskNo"));
			amazonPricePanel.down("#status").setValue(sm.getSelection()[0].get("status"));

			newWin.show();
		}

		function rightClickFn(view, rec, node, index, e) {
            e.stopEvent();
            grid.getSelectionModel().select(rec);
            rightClickMenu.showAt(e.getXY());
            return false;
        }

        var rightClickMenu = new Ext.menu.Menu( {
            id : 'rightClickCont',
            items : [ {
                id:'rMenu0',
                iconCls : 'add',
                text : 'タスク追加',
                handler:addTask
            },{
                id:'rMenu1',
                iconCls : 'remove',
                text : 'タスク一時停止',
                handler:pauseTask
            }, {
                id:'rMenu2',
                iconCls : 'start',
                text : 'タスク再開',
                handler:restartTask
            }, {
                id:'rMenu3',
                iconCls : 'delete',
                text : 'タスク削除',
                handler:deleteTask
            }, {
                id:'rMenu4',
                iconCls : 'edit',
                text : 'タスク修正',
                handler:editTask
            }, {
                id:'rMenu5',
                iconCls : '',
                text : '商品ページをみる',
                handler:showItemPage
            }]
        });

        function showItemPage(){
        	var sm = grid.getSelectionModel();
        	var url="http://www.amazon.co.jp/gp/offer-listing/"+sm.getSelection()[0].get("amazonItemId")+"/";

        	var condition =sm.getSelection()[0].get("condition");
        	if(condition=="1"){
        		url+="sr=/qid=/ref=olp_tab_new?ie=UTF8&colid=&coliid=&condition=new&me=&qid=&seller=&sr=";
        	}else if(condition=="2"){
        		url+="sr=/qid=/ref=olp_tab_used?ie=UTF8&colid=&coliid=&condition=used&me=&qid=&seller=&sr=";
        	}
        	window.open(url);
        }

		var newGrid =Ext.create('Ext.panel.Panel', {
			title : 'Amazon',
			layout : 'auto',
			items : [  grid ],
			renderTo : 'bodyarea'
		});

		var labelWidth=120;

		var settingPanel=Ext.create('Ext.form.Panel', {
			region : 'center',
			frame : true,
			bodyStyle : 'padding:5px 5px 0',
			width : 350,
			fieldDefaults : {
				msgTarget : 'side',
				labelWidth : 75
			},
//			defaults : {
//				anchor : '100%'
//			},
			items : [  {
				xtype : 'fieldcontainer',
				collapsible: true,
				combineErrors : true,
				msgTarget : 'side',
	            defaultType: 'numberfield',
				items : [{
	                fieldLabel: '間隔時間（分）',
	                labelSeparator:'：',
	                id: 'kankakuTime'
	            }]
			}],
			buttons : [ {
				text : 'Save',
                handler: function() {
				var kankakuTime =settingPanel.down("#kankakuTime").getValue();
				if(kankakuTime>5){
					Ext.Ajax.request({
					    url: 'doSetKankakuTime/',
					    params:{
							kankakuTime:kankakuTime
						},
					    success: function(response, opts) {
							if(response.responseText=="success"){
								settingWin.close();
							}
					    },
					    failure: function(response, opts) {
					        console.log('server-side failure with status code ' + response.status);
					    }
					});
				}else{
					Ext.Msg.alert('error', '間隔時間を５分以上にしてください。');
				}
			}
			}]
		});
		var amazonPricePanel=Ext.create('Ext.form.Panel', {
			region : 'center',
			frame : true,
			bodyStyle : 'padding:5px 5px 0',
			width : 350,
			fieldDefaults : {
				msgTarget : 'side',
				labelWidth : 70
			},
			defaultType : 'textfield',
			defaults : {
				anchor : '100%'
			},

			items : [  {
				xtype : 'fieldset',
				title: 'Amazon',
				collapsible: true,
				combineErrors : true,
				msgTarget : 'side',
				layout : 'anchor',
		          defaults: {
	                anchor: '100%'
	            },
	            defaultType: 'textfield',
				items : [
				{
	                fieldLabel: 'コンディション',
	                xtype:'radiogroup',
	                labelWidth : 100,
	                labelSeparator:'：',
	                id: 'condition',
	                items: [
	                        { boxLabel: '新品', name: 'rb', inputValue: '1' , checked: true},
	                        { boxLabel: '中古', name: 'rb', inputValue: '2' }
//	                        ,{ boxLabel: '全部', name: 'rb', inputValue: '3' , checked: true}
	                    ]
	            },{
	                fieldLabel: 'ASIN',
	                labelSeparator:'：',
	                id: 'asin'
	            },{
	                fieldLabel: '商品名',
	                labelSeparator:'：',
	                readOnly:true,
	                readOnlyCls:'color=gray',
	                id: 'amazonItemName'
	            },{
	                fieldLabel: '最安店舗',
	                labelSeparator:'：',
	                readOnly:true,
	                readOnlyCls:'color: gray',
	                id: 'amazonShop'
	            },{
	                fieldLabel: '最安価格',
	                labelSeparator:'：',
	                readOnly:true,
	                readOnlyCls:'color: gray',
	                id: 'amazonItemPrice'
	            },{
	                fieldLabel: '送料',
	                labelSeparator:'：',
	                readOnly:true,
	                readOnlyCls:'color: gray',
	                id: 'amazonItemShippingPrice'
	            }, {
	                xtype: 'button',
	                text : 'Amazonの商品情報を取得',
	                margin : '0 0 10px 0',
	                handler: function() {
	            	var myMask = new Ext.LoadMask(newWin, {msg:"Please wait..."});
	            	myMask.show();
						Ext.Ajax.request({
						    url: 'doGetAmazonItemInfo/',
						    params:{
								amazonItemId:amazonPricePanel.down("#asin").getValue(),
								condition:amazonPricePanel.down("#condition").getValue()
							},
						    success: function(response, opts) {
								if(response.responseText){
									var result = response.responseText.split(",");
									amazonPricePanel.down("#amazonItemName").setValue(result[0]);
									amazonPricePanel.down("#amazonItemPrice").setValue(result[1]);
									amazonPricePanel.down("#amazonShop").setValue(result[2]);
									amazonPricePanel.down("#amazonItemShippingPrice").setValue(result[3]);
									amazonPricePanel.down("#asin1").setValue(amazonPricePanel.down("#asin").getValue());
									myMask.hide();
								}
						    },
						    failure: function(response, opts) {
						    	amazonPricePanel.down("#amazonItemName").setValue("取得失敗,ASINをちゃんと確認してください。");
								amazonPricePanel.down("#amazonItemPrice").setValue("");
								amazonPricePanel.down("#amazonShop").setValue("");
								amazonPricePanel.down("#amazonItemShippingPrice").setValue("");
						        console.log('server-side failure with status code ' + response.status);
						        myMask.hide();
						    }
						});
	            	}
	            }]
			}, {
				xtype : 'fieldset',
				title: '当店商品情報',
				collapsible: true,
				combineErrors : true,
				msgTarget : 'side',
				layout : 'anchor',
		          defaults: {
	                anchor: '100%'
	            },
	            defaultType: 'textfield',
				items : [
				{
	                fieldLabel: 'ASIN',
	                labelSeparator:'：',
	                readOnly:true,
	                id: 'asin1'
	            },{
	                fieldLabel: '出品者SKU',
//	                labelWidth:labelWidth,
	                labelSeparator:'：',
	                id: 'sku'
	            },{
	                fieldLabel: 'コンディション',
	                labelWidth : 100,
	                labelSeparator:'：',
//	                readOnly:true,
	                id: 'shopItemCondition'
	            },{
	                fieldLabel: '商品名',
	                labelSeparator:'：',
//	                readOnly:true,
	                id: 'shopItemName'
	            },{
	                fieldLabel: '現在価格',
	                labelSeparator:'：',
//	                readOnly:true,
	                id: 'shopItemPrice'
	            },{
	                fieldLabel: '在庫数',
	                labelSeparator:'：',
//	                readOnly:true,
	                id: 'shopItemQuantity'
	            }, {
	                xtype: 'button',
	                text : '当店の商品情報を取得',
	                margin : '0 0 10px 0',
	                handler: function() {
	            	var amazonItemId =amazonPricePanel.down("#asin1").getValue();
	            	var sku =amazonPricePanel.down("#sku").getValue();
	            	if(amazonItemId<=0){
	            		Ext.Msg.alert('error', 'ASINを確認してください。');
	            	}else if(sku<=0){
	            		Ext.Msg.alert('error', 'SKUを確認してください。');
	            	}else{
		            	var myMask = new Ext.LoadMask(newWin, {msg:"Please wait..."});
		            	myMask.show();
							Ext.Ajax.request({
							    url: 'doGetShopItemInfo/',
							    params:{
								sku:sku,
								amazonItemId:amazonItemId
								},
							    success: function(response, opts) {
									if(response.responseText){
										var result = response.responseText.split(",");
										amazonPricePanel.down("#shopItemName").setValue(result[0]);
										amazonPricePanel.down("#shopItemPrice").setValue(result[1]);
										amazonPricePanel.down("#shopItemCondition").setValue(result[2]);
										amazonPricePanel.down("#shopItemQuantity").setValue(result[3]);
									}
									myMask.hide();
							    },
							    failure: function(response, opts) {
							    	myMask.hide();
							    	amazonPricePanel.down("#shopItemName").setValue("取得失敗,システム商品コードをちゃんと確認してください。");
							        console.log('server-side failure with status code ' + response.status);
							    }
							});
	            	}

	            }}]
			}, {
				xtype : 'fieldcontainer',
				combineErrors : true,
				msgTarget : 'side',
				layout : 'hbox',
				items : [ {
					xtype : 'displayfield',
					value : '最低価格：',
					margin : '0 0 0 0',
					width:90
				}, {
					id : 'minPrice',
					xtype : 'numberfield',
					width : 150
				} ,{
					id : 'taskNo',
			        xtype: 'hiddenfield',
			        value: ''

				} ,{
					id : 'status',
			        xtype: 'hiddenfield',
			        value: ''
				} ]
			} ],

			buttons : [ {
				text : '保存',
                handler: function() {
					var taskNo=amazonPricePanel.down("#taskNo").getValue();
					var status=amazonPricePanel.down("#status").getValue();
					var amazonItemId=amazonPricePanel.down("#asin").getValue();
					var amazonItemName=amazonPricePanel.down("#amazonItemName").getValue();
					var amazonItemPrice=amazonPricePanel.down("#amazonItemPrice").getValue();
					var minPrice=amazonPricePanel.down("#minPrice").getValue();
					var sku=amazonPricePanel.down("#sku").getValue();
					var shopItemName=amazonPricePanel.down("#shopItemName").getValue();
					var shopItemPrice=amazonPricePanel.down("#shopItemPrice").getValue();
					var quantity=amazonPricePanel.down("#shopItemQuantity").getValue();
					var minPrice=amazonPricePanel.down("#minPrice").getValue();
					var condition=amazonPricePanel.down("#condition").getValue();
					if(minPrice<=0){
						Ext.Msg.alert('error', '最低価格を確認してください。');
					}else if(amazonItemName.length<=0){
						Ext.Msg.alert('error', 'Amazone商品情報を確認してください。');
					}else if(shopItemName.length<=0){
						Ext.Msg.alert('error', '当店商品情報を確認してください。');
					}else{
						var requestUrl="";
						if(taskNo==""){
							requestUrl="addTask";
						}else{
							requestUrl="doUpdateTask";
						}

						Ext.Ajax.request({
						    url: requestUrl,
						    params:{
								taskNo:taskNo,
								status:status,
								amazonItemId:amazonItemId,
								amazonItemName:amazonItemName,
								amazonItemPrice:amazonItemPrice,
								sku:sku,
								shopItemName:shopItemName,
								shopItemPrice:shopItemPrice,
								quantity:quantity,
								minPrice:minPrice,
								condition:condition
							},
						    success: function(response, opts) {
								if(response.responseText=="success"){
									newWin.close();
									store.load();
								}else if (response.responseText=="exist") {
									Ext.Msg.alert('error', '登録済みの商品です、重複登録ができません。');
								}
						    },
						    failure: function(response, opts) {
						        console.log('server-side failure with status code ' + response.status);
						    }
						});
					}
				}
			}, {
				text : '取消',
				handler: function() {
					newWin.close();
				}
			} ]
		});

		var newWin = Ext.create('widget.window', {
			title : 'タスク新規作成',
			closable : true,
			closeAction : 'hide',
			width : 530,
			height : 600,
			layout : 'border',
			bodyStyle : 'padding: 5px;',
			items : amazonPricePanel
		});

		var settingWin = Ext.create('widget.window', {
			title : '間隔時間設定',
			closable : true,
			closeAction : 'hide',
			layout : 'border',
			width : 350,
			height : 130,
			bodyStyle : 'padding: 5px;',
			items : settingPanel
		});

//		var runner = new Ext.util.TaskRunner();
//		runner.start({
//		    run: function(){
//				var selectNode =grid.getSelectionModel().getSelection();
//				store.load({callback :function(){
//						if(selectNode.length>0){
//							grid.getSelectionModel().select(selectNode[0].index);
//						}
//					}
//				});
//			},
//			interval: 10000
//		});
	});
